<?php
namespace app\controller;

use app\BaseController;
use app\message;
use app\model\CluePerson;
use app\model\Operate;
use app\model\OrderDealChargeback;
use app\model\OrderEnterpriseCertificateBusiness;
use app\model\OrderEnterpriseCertificateRegister;
use app\model\OrderEnterpriseCompany;
use app\model\OrderEnterpriseExchange;
use app\model\OrderOtherCertificateBusiness;
use app\model\PublicSaleRule;
use app\model\SystemBusiness;
use app\model\SystemCertificate;
use app\model\SystemMenu;
use app\model\SystemMenuDataPower;
use app\model\SystemNotice;
use app\model\SystemOperateLog;
use app\model\SystemSign;
use app\model\SystemTargetLib;
use app\model\User;
use app\model\UserOrganization;
use app\model\WorkPlan;
use app\Request;
use app\service\Certificate;
use app\service\Excel;
use app\service\Power;
use app\service\Rsa;
use app\service\System;
use app\stateData;
use DateInterval;
use DatePeriod;
use DateTime;
use GatewayClient\Gateway;
use PhpOffice\PhpSpreadsheet\Calculation\Financial\Securities\Price;
use think\App;
use think\console\command\optimize\Route;
use think\Exception;
use think\facade\Log;
use think\facade\View;
use think\File;
use Workerman\Connection\TcpConnection;
use Workerman\Worker;
use Workerman\Timer;

use think\worker\Server;
use think\facade\Db;

class Index extends BaseController
{

    private $erleiCertificate_id;

    public function __construct(App $app, SystemCertificate $certificateModel)
    {
        parent::__construct($app);
        //赋值二类证书id
        $this->erleiCertificate_id = $certificateModel->getWhereCertificateIdModel('Ⅱ');
    }
    /**
     * 处理筛选部门或人员数据
     * @param $department_id //部门ID
     * @param $user_id //人员ID
     * @return array //返回员工ID数组
     */
    public function handleUserIds($department_id, $user_id)
    {
        $user_ids = [];
        if ($user_id) return [$user_id];
        if ($department_id) {
            //获取部门下所有的部门下的人
            $userOrganization = new UserOrganization();
            $department_ids = $userOrganization->getDataRangeDepartmentList([], $department_id);
            $department_ids[] = $department_id;
            sort($department_ids);
            $user = new User();
            $userList = $user->getDepartmentUserList($department_ids);
            $user_ids = array_column($userList, 'id');
        }
        return $user_ids;
    }

    public function index(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderEnterpriseExchange            $exchange,
        OrderEnterpriseCertificateBusiness $business,
        OrderOtherCertificateBusiness      $other,
        WorkPlan                           $workPlan,
        User                               $user,
        UserOrganization                   $organization,
        Power                              $power,
        SystemMenuDataPower                $dataPower,
        SystemTargetLib                    $target,
        System                             $systemService,
        SystemSign $systemSignModel
    ){
        $uid = $request->param('user_login_id');//登录人ID
        $type = $request->param('type');//筛选 1-今日 2-本周 3-当月 4-本季度 5-本年
        $startDate = $request->param('startDate');//开始时间
        $endDate = $request->param('endDate');//结束时间
        $department_id = $request->param('oid');//部门
        $user_id = $request->param('user_id');//人员
        //查询用户基础数据
        $userFindData = $user->getIdUserData($uid);
        //获取时间
        $dateArray = handleStartStopDate($type, $startDate, $endDate);
        /**
         * 获取当月签到天数
         */

        $moonStart = date('Y-m-1');
        $moonEnd = date ("Y-m-t");
        $dayNum = $systemSignModel->whereBetweenTime ('create_date',$moonStart,$moonEnd)->count ();

        $startDate = $dateArray['startDate'];
        $endDate = $dateArray['endDate'];
        //如果部门和人员都为空 根据数据可见范围获取当前账号管理的人员ID数组 如果不为空 根据部门或人员获取人员ID数组
        $uidArr = !$department_id && !$user_id ? $power->getUserDataRange($uid) : $this->handleUserIds($department_id, $user_id);

        //当前账号数据可见范围
        $range = $dataPower->getDataRangeModel($userFindData['level_id']['id']);
        //如果uid 为admin 数据可见范围为全公司
        if ($userFindData['username'] === stateData::$_admin['acc']) {
            $range = 1;
        }
        /**
         * 请选择公司-部门-人员 下拉框值
         */
        switch ($range) {
            case 1: //总公司
                $selectVal = $systemService->getOrgTypeUserList($organization->getStructure()->toArray());
//                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['department_id']['id']),$userFindData['department_id']['id']);
                break;
            case 2://分公司
                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['company_id']['id']), $userFindData['company_id']['id']);
                break;
            case 3://部门
                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['department_id']['id']), $userFindData['department_id']['id']);
                break;
            case 4://个人
                $selectVal = '';
                break;
            default:
        }
        //汇总
//        $result['select_val'] = $selectVal;

        /**
         * 总业绩
         */
        $result['total'] = number_format($this->getTotal($startDate, $endDate, $uidArr), 2);

        /**
         * 订单量
         */
        //企业证书注册
        $enterCount = $company->getOrderNumModel($startDate, $endDate, $uidArr);

        //企业倒证
        $exchangeCount = $exchange->getOrderNumModel($startDate, $endDate, $uidArr);
        //证书办理
        $otherCount = $other->getOrderNumModel($startDate, $endDate, $uidArr);
        //企业证书
        $businessCount = $business->getOrderNumModel($startDate, $endDate, $uidArr);

        $result['totalddl'] = $enterCount + $exchangeCount + $otherCount + $businessCount;

        /**
         * 待沟通
         */
        $result['dgt'] = $workPlan->getCompletewCount($startDate, $endDate, $uidArr);


        /**
         * 二类月目标业绩
         */

        //查询二类证书专业
//        $cerIdArr = $certificate->getCertificateChildsIdStr ($this->erleiCertificate_id, $certificateData);
        $cerIdArr = $this->erleiCertificate_id;

        //本月时间戳
        $dates = date('Y-m-1');
//        $monthMoney = 10000;
        $monthDay = date('t', strtotime(date('y-m-d')));
        //查询月目标业绩
        //部门
        if ($range == 3) {
            $monthTarget = $target->getMoonDataModel($dates, $userFindData['department_id']['id'], 2);
        }
        //分公司
        if ($range == 2) {
            $fgsId = $systemService->getOrgFgsId($userFindData['department_id']['id']);
            $monthTarget = $target->getMoonDataModel($dates, $fgsId, 2);
        }

        //总公司
        if ($range == 1) {
            if ($userFindData['username'] === 'admin') {
                $zgsId = $organization->getZgsId();
            } else {
                $zgsId = $systemService->getOrgZgsId($userFindData['department_id']['id']);
            }
            $monthTarget = $target->getMoonDataModel($dates, $zgsId, 2);
        }
        //个人
        if ($range == 4) {
            $monthTarget = $target->getMoonDataModel($dates, $userFindData['id'], 1);
        }

        if (!empty($monthTarget)) {
            //目标、天数
            if (!$monthTarget['weekday']) {
                $monthTarget['weekday'] = 0;
            }
            if (!$monthTarget['target']) {
                $monthTarget['target'] = 0;
            }
            $result['two_moon_type_target'] = $monthTarget;
        } else {
            $result['two_moon_type_target']['weekday'] = $monthDay;
            $result['two_moon_type_target']['target'] = 0;
        }

        //当月总天数
        $result['two_moon_type_target']['moon_day'] =  $target->getValueTargetDayModel ($dates,'',3,3);;
        //当前天数
        $result['two_moon_type_target']['today'] = $dayNum;
        //时间进度百分比
        if ($result['two_moon_type_target']['moon_day'] == 0) {
            $result['two_moon_type_target']['moon_day'] = 0;
            $result['two_moon_type_target']['percentage_day'] = round($result['two_moon_type_target']['today'] / 1 * 100, 2);
        } else {
            $result['two_moon_type_target']['percentage_day'] = round($result['two_moon_type_target']['today'] / $result['two_moon_type_target']['moon_day'] * 100, 2);
        }

        //本月开始
        $monthStartDate = date('Y-m-01');
        //本月结束
        $monthEndDate = date('Y-m-d', strtotime(date('Y-m-01') . ' 1 month -1 day'));

        //企业证书注册
        $monthEnterData = $company->getSummary($monthStartDate, $monthEndDate, $uidArr, $cerIdArr);
        //企业倒证
        $monthExchangeData = $exchange->getSummaryModel($monthStartDate, $monthEndDate, $uidArr, $cerIdArr);
        //证书办理
        $monthOtherData = $other->getSummaryModel($monthStartDate, $monthEndDate, $uidArr, $cerIdArr);
        //企业证书
        $monthBusinessData = $business->getSummaryModel($monthStartDate, $monthEndDate, $uidArr); //企业证书没有证书分类

        $result['two_moon_type_target']['all_price'] = $monthExchangeData['performance_sum'] + $monthOtherData['performance_sum'] + $monthBusinessData + $monthEnterData;

        //获取退单金额
        $tdPrice = $this->getChargeback($monthStartDate, $monthEndDate, $uidArr, $this->erleiCertificate_id);

        $result['two_moon_type_target']['all_price'] += $tdPrice;
//        $cerId = explode (',', $cerIdArr);
//        //企业证书注册业绩计算
//        foreach ($monthEnterData as $Datums) {
//            $cid = $certificateModel->getWhereCertificateIdModel($Datums['certificate_leixing']);
//            if ($cid == $this->erleiCertificate_id){
//                $result['two_moon_type_target']['all_price'] += $Datums['performance_all'];
//                $result['two_moon_type_target']['all_price'] += $tdPrice;
//            }
//        }


        //达成距离
        if (isset($result['two_moon_type_target']['target']) && !empty($result['two_moon_type_target']['target'])) {

            $result['two_moon_type_target']['distance'] = round($result['two_moon_type_target']['target'] - $result['two_moon_type_target']['all_price'], 2);

            //达成进度百分比
            $result['two_moon_type_target']['percentage_jindu'] = round($result['two_moon_type_target']['all_price'] / $result['two_moon_type_target']['target'] * 100);
            if ($result['two_moon_type_target']['percentage_jindu'] > 100) {
                $result['two_moon_type_target']['percentage_jindu'] = 100;
            } else if ($result['two_moon_type_target']['percentage_jindu'] < 0) {
                $result['two_moon_type_target']['percentage_jindu'] = 0;
            }
            //达成差距百分比
            $result['two_moon_type_target']['percentage_chaju'] = round($result['two_moon_type_target']['distance'] / $result['two_moon_type_target']['target'] * 100);
            if ($result['two_moon_type_target']['percentage_chaju'] > 100) {
                $result['two_moon_type_target']['percentage_chaju'] = 100;
            } else if ($result['two_moon_type_target']['percentage_chaju'] < 0) {
                $result['two_moon_type_target']['percentage_chaju'] = 0;
            }
        } else {
            $result['two_moon_type_target']['distance'] = 100;
            //达成进度百分比
            $result['two_moon_type_target']['percentage_jindu'] = 100;
            //达成差距百分比
            $result['two_moon_type_target']['percentage_chaju'] = 100;
        }


        /**
         * 二类周目标业绩
         */
//        $meekMoney = 1000;
        //每周起止时间
        $weekDate = get_weekinfo(date('Y-m'));
        $whereDate = '';
        foreach ($weekDate as $item) {
            if (strtotime($item['start']) <= time() && time() <= strtotime($item['end'])) {
                $whereDate = $item['start'];
                break;
            }
        }

        //当前账号如果数据可见范围 查询周目标业绩
//        $range = $dataPower->getDataRangeModel ($userFindData['level_id']);
//        //获取当月一共几周
//        $totalWeek = weekOfMonth (strtotime (date ('Y-m')), strtotime (date ('Y-m-1')));
//
//        //获取当前日期是当月第几周
//        $dangqianWeek = weekOfMonth (strtotime (date ('Y-m')), strtotime (date ('Y-m-d')));
//        $qdWeek = $totalWeek-$dangqianWeek;

        //数据库查询field
        $field = "moon_target";
        $field2 = 'moon_day';
        $meek_day = 7;

        //获取当前周对应的目标
        //部门
        if ($range == 3) {
            //拼接查询本周字段
            $meekTarget = $target->getCircsModel($whereDate, $field, $userFindData['department_id']['id'], 2, 2);
            $meek_day = $target->getCircsModel($whereDate, $field2, $userFindData['department_id']['id'], 2, 2);
        }
        //分公司
        if ($range == 2) {
            $fgsId = $systemService->getOrgFgsId($userFindData['department_id']['id']);
            $meekTarget = $target->getCircsModel($whereDate, $field, $fgsId, 2, 2);
            $meek_day = $target->getCircsModel($whereDate, $field2, $fgsId, 2, 2);

        }
        //总公司
        if ($range == 1) {
            if ($userFindData['username'] === 'admin') {
                $zgsId = $organization->getZgsId();
            } else {
                $zgsId = $systemService->getOrgZgsId($userFindData['department_id']['id']);
            }
            $meekTarget = $target->getCircsModel($whereDate, $field, $zgsId, 2, 2);
            $meek_day = $target->getCircsModel($whereDate, $field2, $zgsId, 2, 2);
        }
        //个人
        if ($range == 4) {
            $meekTarget = $target->getCircModel($whereDate, $field, $userFindData['id'], 1, 2);
            $meek_day = $target->getCircModel($whereDate, $field2, $userFindData['id'], 1, 2);
        }

//        if(!empty(json_decode ($meekTarget, false))){
//            $result['two_circ_type_target'] = $meekTarget;
//        }else{
//            $result['two_circ_type_target']['moon_target'] = 0;
//        }

        if (!empty($meekTarget)) {
            $result['two_circ_type_target']['moon_target'] = $meekTarget;
        } else {
            $result['two_circ_type_target']['moon_target'] = 0;
        }

        //当周总天数
        $result['two_circ_type_target']['meek_day'] = $meek_day;

        //当前天数
        $result['two_circ_type_target']['today'] = date("N");

        //时间进度百分比
        if (!$result['two_circ_type_target']['meek_day']) {
            $result['two_circ_type_target']['meek_day'] = 7;
        }
        $result['two_circ_type_target']['percentage_day'] = round($result['two_circ_type_target']['today'] / $result['two_circ_type_target']['meek_day'] * 100, 2);

        //本周开始
        $meekStart = date('Y-m-d', strtotime('this week Monday'));
        //本周结束
        $meekEnd = date('Y-m-d', strtotime('this week Sunday'));

        //企业证书注册
        $weekEnterData = $company->getSummary($meekStart, $meekEnd, $uidArr);

        //企业倒证
        $weekExchangeData = $exchange->getSummaryModel($meekStart, $meekEnd, $uidArr, $cerIdArr);
        //证书办理
        $weekOtherData = $other->getSummaryModel($meekStart, $meekEnd, $uidArr, $cerIdArr);

        //企业证书
        $weekBusinessData = $business->getSummaryModel($meekStart, $meekEnd, $uidArr);

        //获取退单金额
        $tdsPrice = $this->getChargeback($monthStartDate, $monthEndDate, $uidArr, $this->erleiCertificate_id);

        $result['two_circ_type_target']['all_price'] = $weekExchangeData['performance_sum'] + $weekOtherData['performance_sum'] + $weekBusinessData + $weekEnterData;

        $result['two_circ_type_target']['all_price'] += $tdsPrice;

        //企业证书注册业绩处理 单位价/人数-人才收证价
//        foreach ($weekEnterData as $Datum) {
//            $cid = $certificateModel->getWhereCertificateIdModel($Datum['certificate_leixing']);
//            if ($cid == $this->erleiCertificate_id){
//                $result['two_circ_type_target']['all_price'] += $Datum['performance_all'];
//                $result['two_circ_type_target']['all_price'] += $tdsPrice;
//            }
//        }

        //达成距离
        $result['two_circ_type_target']['distance'] = $result['two_circ_type_target']['moon_target'] - $result['two_circ_type_target']['all_price'];
        //达成进度百分比
        if ($result['two_circ_type_target']['moon_target']) {
            $result['two_circ_type_target']['percentage_jindu'] = round($result['two_circ_type_target']['all_price'] / $result['two_circ_type_target']['moon_target'] * 100);
            if ($result['two_circ_type_target']['percentage_jindu'] > 100) {
                $result['two_circ_type_target']['percentage_jindu'] = 100;
            } else if ($result['two_circ_type_target']['percentage_jindu'] < 0) {
                $result['two_circ_type_target']['percentage_jindu'] = 0;
            }
            //达成差距百分比
            $result['two_circ_type_target']['percentage_chaju'] = round($result['two_circ_type_target']['distance'] / $result['two_circ_type_target']['moon_target'] * 100);
            if ($result['two_circ_type_target']['percentage_chaju'] > 100) {
                $result['two_circ_type_target']['percentage_chaju'] = 100;
            } else if ($result['two_circ_type_target']['percentage_chaju'] < 0) {
                $result['two_circ_type_target']['percentage_chaju'] = 0;
            }
        } else {
            $result['two_circ_type_target']['percentage_chaju'] = 100;
            $result['two_circ_type_target']['percentage_jindu'] = 100;

        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    /**
     * 二类业绩排行榜
     */

    public function getErLeiPhb(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderEnterpriseExchange            $exchange,
        OrderEnterpriseCertificateBusiness $business,
        OrderOtherCertificateBusiness      $other,
        OrderEnterpriseCertificateRegister $register,
        WorkPlan                           $workPlan,
        Certificate                        $certificate,
        SystemCertificate                  $certificateModel,
        SystemBusiness                     $businessYw,
        SystemCertificate                  $systemCertificate,
        User                               $user,
        UserOrganization                   $organization,
        PublicSaleRule                     $saleRule,
        Power                              $power,
        SystemMenuDataPower                $dataPower,
        SystemTargetLib                    $target,
        System                             $systemService,
        System                             $system
    ){

        $uid = $request->param('user_login_id');

        //查询用户基础数据
        $userFindData = $user->getIdUserData($uid);
        $selectVal = [];
        //查询二类证书专业
        $certificateData = $certificateModel->getCertificateListModel();
        $cerIdArr = $certificate->getCertificateChildsIdStr($this->erleiCertificate_id, $certificateData);
        $cerId = $this->erleiCertificate_id;
        //当前账号数据可见范围
        $range = $dataPower->getDataRangeModel($userFindData['level_id']['id']);

        /**
         * 请选择公司-部门-人员 下拉框值
         */

        switch ($range) {
            case 1: //总公司
                $selectVal = $systemService->getOrgTypeUserList($organization->getStructure());
//                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['department_id']['id']),$userFindData['department_id']['id']);
                break;
            case 2://分公司
                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['company_id']['id']), $userFindData['company_id']['id']);
                break;
            case 3://部门
                $selectVal = $systemService->getOrgTypeUserList($organization->getOidParentDataModel($userFindData['department_id']['id']), $userFindData['department_id']['id']);
                break;
            case 4://个人
                $selectVal = '';
                break;
        }

        //汇总
        $result['select_val'] = $selectVal;

        $oid = $request->get('oid');
        $id = $request->get('id');

        if (empty($id)) { //查询公司部门
            if (empty($oid)){
                $idArr = $user->getAllUidModel();
            }else{
                $oidArr = $system->getOrgIdStr($oid, $organization->getStructure());
                $idArr = $user->getUidArrDataModel($oidArr);
            }
        } else { //查询个人
            $idArr = [$id];
        }

        //时间区间条件
        $paramDate = $request->param('date') ?: 1;

        //开始时间
        $startDate = $request->param('start_date');
        //结束时间
        $endDate = $request->param('end_date');

        if (!$startDate || !$endDate) {
            if ($paramDate == 1) {
                //开始时间
                $startDate = date('Y-m-d') . ' 00:00:00';
                //结束时间
                $endDate = date('Y-m-d') . ' 23:59:59';
                if(!$request->param('date')){
                    //获取当前账号管理的人员id数组
                    $idArr = $power->getUserDataRange($uid);
                }
            } elseif ($paramDate == 2) {

                $w = date("w");

                $startDate = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - $w + 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'))) . ' 23:59:59';
                //获取当前账号管理的人员id数组
                $idArr = $power->getUserDataRange($uid);
            } elseif ($paramDate == 3) {
                $startDate = date('Y-m-d', mktime(0, 0, 0, date("m"), 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(23, 59, 59, date('m'), date('t'), date('Y')) - 1) . ' 23:59:59';
                //获取当前账号管理的人员id数组
                $idArr = $power->getUserDataRange($uid);
            } elseif ($paramDate == 4) {
                $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3, 1, date("Y")));//本季度未最后一月天数

                $startDate = date('Y-m-d H:i:s', mktime(0, 0, 0, date('n') - (date('n') - 1) % 3, 1, date('Y'))) . ' 00:00:00';
                $endDate = date('Y-m-d H:i:s', mktime(23, 59, 59, date('n') + (date('n') - 1) % 3, $getMonthDays, date('Y'))) . ' 23:59:59';
                //获取当前账号管理的人员id数组
                $idArr = $power->getUserDataRange($uid);
            } elseif ($paramDate == 5) {
                $startDate = date('Y-m-d', mktime(0, 0, 0, 1, 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(0, 0, 0, 1, 1, date("Y") + 1) - 1) . ' 23:59:59';
                //获取当前账号管理的人员id数组
                $idArr = $power->getUserDataRange($uid);
            }
        } else {
            //获取当前账号管理的人员id数组
            $idArr = $power->getUserDataRange($uid);

            $startDate .= ' 00:00:00';
            $endDate .= ' 23:59:59';
        }

        /**
         * 如果当前登陆用户数据权限为个人  查询所有人当天排行数据
         */
        if ($range == 4){
            $userPowerIdData = $user->getAllUidModel();
            $phbStartDate = date('Y-m-d') . ' 00:00:00';
            $phbEndDate = date('Y-m-d') . ' 23:59:59';
        }else{
            $userPowerIdData = $idArr;
            $phbStartDate = $startDate;
            $phbEndDate = $endDate;
        }

        //获取id所有用户id 部门 名称
        $userData = $user->getAllUserIdNicknameOrgModel($userPowerIdData);

        //企业证书注册
        $monthEnterPhb = $company->getPhbModel($phbStartDate, $phbEndDate, $userPowerIdData, $cerId);
        //企业倒证
        $monthExchangePhb = $exchange->getPhbModel($phbStartDate, $phbEndDate, $userPowerIdData, $cerId);
        //证书办理
        $monthOtherPhb = $other->getPhbModel($phbStartDate, $phbEndDate, $userPowerIdData, $cerId);
        //企业证书
        $weekBusinessData = $business->getPhbModel($phbStartDate, $phbEndDate, $userPowerIdData);


        //合并业绩
        $result['phb_data'] = $this->Consolidated($userData, $monthOtherPhb, $monthExchangePhb, $monthEnterPhb, $weekBusinessData);


        /**
         * Ⅰ类业绩统计 + 排行
         */
        //查询公示栏所有规则
        $saleRuleData = $saleRule->getBetweenRule();
        //拼接证书名称
        $cerName = [];
        $uidStr = '';
        foreach ($saleRuleData as &$item) {
            //证书
            $cerStr = explode(',', $item['certificate_id']);
            $item['certificate_name'] = '';
            //所有证书负责人
            $uidStr .= $item['uid'] . ',';
            foreach ($cerStr as $cerItem) {
                $item['certificate_name'] .= $systemCertificate->getWhereIdCertificateModel($cerItem) . '、';
            }

            $item['certificate_name'] = rtrim($item['certificate_name'], '、');
            $cerName[] = $item['certificate_name'];
        }


        //统计业绩
        //证书负责人字符串转数组
        $uidArr = array_values(array_unique(explode(',', $uidStr)));

        $arr = [];
        //补充统计数据
        foreach ($uidArr as $key => $itema) {
            if (!$itema) {
                continue;
            }
            //拼接用户基础数据
            $arr[$key]['nickname'] = $user->getIdNickName($itema);
            $arr[$key]['value'] = [];

            foreach ($saleRuleData as $k => $items) {
                $allPrice = 0;
                $cerId = 0;
                //证书
                $cerStr = explode(',', $items['certificate_id']);
                foreach ($cerStr as $cerItem) {
                    //最后一级证书id
                    $cerId = $cerItem;
                }

                //企业证书注册
                $yileiEnterPhb = $company->getYileiWorkCount($startDate, $endDate, $cerId, $itema);

                //企业倒证
                $yileiExchangePhb = $exchange->getYileiWorkCount($startDate, $endDate, $cerId, $itema);

                //证书办理
                $yileiOtherPhb = $other->getYileiWorkCount($startDate, $endDate, $cerId, $itema);

                if ($yileiEnterPhb[0]['all_out_price']) {
                    $allPrice += (int)$yileiEnterPhb[0]['all_out_price'];
                }
                if ($yileiExchangePhb[0]['all_out_price']) {
                    $allPrice += (int)$yileiExchangePhb[0]['all_out_price'];
                }
                if ($yileiOtherPhb[0]['all_out_price']) {
                    $allPrice += (int)$yileiOtherPhb[0]['all_out_price'];
                }
                $arr[$key]['value'][] = $allPrice;

            }
        }

        //汇总
        $result['yileitongji']['keyword'] = $cerName;
        $result['yileitongji']['data'] = $arr;

        //获取当前账号管理的人员id数组
        $idArr = $power->getUserDataRange($uid);
        /**
         * Ⅱ类业务占比
         */
        $busin = $other->getErLeiBusinessModel($startDate, $endDate, $idArr);

        //证书注册
        $enterData = $company->getErleiZhanBiSummary($startDate, $endDate, $idArr);

        //倒证
        $dzData = $exchange->getErleiZhanBiModel($startDate, $endDate, $idArr, $this->erleiCertificate_id);

        $regNum = 0;
        $regNum += $dzData['performance_sum'];
        foreach ($enterData as $enterDatum) {
            //如果不满足证书条件跳出循环
            if (is_numeric($enterDatum['certificate_leixing'])) {
                if ($enterDatum['certificate_leixing'] == $this->erleiCertificate_id) {
                    $regNum += $enterDatum['performance'];
                    break;
                }
            } else {
                $cid = $certificateModel->getWhereCertificateIdModel($enterDatum['certificate_leixing']);
                if ($cid == $this->erleiCertificate_id) {

                    $regNum += $enterDatum['performance'];
                    break;
                }
            }
        }
        //添加证书注册占比
        if ($regNum) {
            $busin[] = [
                'price' => $regNum,
                'business_id' => [
                    'id' => '',
                    'text' => '证书注册'
                ]
            ];
        }

        $totalAmount = 0;
        $buData = [];
        unset($item);
        foreach ($busin as $key => $item) {
            $buData[$key]['business_name'] = $item['business_id']['text'];
            $buData[$key]['price'] = $item['price'];
            $totalAmount += $item['price'];
        }

        //计算百分比
        foreach ($buData as $k => &$buDatum) {
            $buDatum['total'] = $totalAmount;
            if ($totalAmount == 0) {
                $buDatum['percentage'] = round($buDatum['price'] / 1 * 100, 2) . '%';
            } else {
                $buDatum['percentage'] = round($buDatum['price'] / $totalAmount * 100, 2) . '%';
            }
        }

        //汇总
        $result['erleiyewuzhanbi'] = $buData;


        /*****
         * 二类业务占比-证书注册下业务统计
         */
        //查询证书注册下所有业务详情
        $regData = $register->getBusinessGroupDataModel();

        foreach ($regData as &$regDatum) {
            $regDatum['performance'] = 0;
            //查看该证书成交的所有人才收证价格
            $perData = $company->getCertificateCode($idArr, $regDatum['certificate_code']);
            if (!empty($perData)) {
                foreach ($perData as $perDatum) {
//                    if ($regDatum['people_num']==0) $regDatum['people_num'] = 1;
                    $regDatum['performance'] += $perDatum['performance'];
                }
            }
        }

        //以业务归类业绩
        $new_arr = array();//存放重装后的数组

        $uname_arr = array();//存放要进行判断的字段

        foreach ($regData as $val) {
            if (in_array($val['business_id']['id'], $uname_arr)) {
                foreach ($new_arr as &$new_val) {
                    if ($new_val['business_id']['id'] == $val['business_id']['id']) {
                        $new_val['performance'] += $val['performance'];

                    }
                }

            } else {
                $uname_arr [] = $val['business_id']['id'];  //当business_id第一次进来的时候，就把 它存在一维数组里面去。用到business_id第二次进去 就能做判断
                $new_arr [] = $val;
            }
        }

        //汇总
        $result['erleiyewuzhanbi_cer_reg'] = $new_arr;

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**********************************************************************
     * Ⅱ类业绩走势图
     */
    public function erleizoushitu(
        Request                            $request,
        OrderEnterpriseCompany             $company,
        OrderEnterpriseExchange            $exchange,
        OrderEnterpriseCertificateBusiness $business,
        OrderOtherCertificateBusiness      $other,
        OrderEnterpriseCertificateRegister $register,
        WorkPlan                           $workPlan,
        Certificate                        $certificate,
        SystemCertificate                  $certificateModel,
        SystemBusiness                     $businessYw,
        SystemCertificate                  $systemCertificate,
        User                               $user,
        UserOrganization                   $organization,
        PublicSaleRule                     $saleRule,
        Power                              $power,
        SystemMenuDataPower                $dataPower,
        SystemTargetLib                    $target,
        System                             $systemService,
        System                             $system
    ){

        $uid = $request->param('user_login_id');
        //查询用户基础数据
        $userFindData = $user->getIdUserData($uid);

        //查询二类证书专业
        $certificateData = $certificateModel->getCertificateListModel();
//        $cerIdArr = $certificate->getCertificateChildsIdStr ($this->erleiCertificate_id, $certificateData);
        $cerIdArr = $this->erleiCertificate_id;

        //当前账号数据可见范围
        $idArr = $power->getUserDataRange($uid);
        //时间区间条件
        $paramDate = $request->param('date') ?: 1;

        //如果有区间条件，先执行区间条件
        if (!empty($request->param('start_date')) && !empty($request->param('end_date'))) {
            //开始时间
            $startDate = $request->param('start_date') . ' 00:00:00';
            //结束时间
            $endDate = $request->param('end_date') . ' 23:59:59';

            $result = $this->getErleizoushituDay($startDate, $endDate, $idArr, $cerIdArr);
        } else {
            if ($paramDate == 1) {
                //开始时间
                $startDate = date('Y-m-d') . ' 00:00:00';
                //结束时间
                $endDate = date('Y-m-d') . ' 23:59:59';
            } elseif ($paramDate == 2) {

                $w = date("w");

                $startDate = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - $w + 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'))) . ' 23:59:59';

            } elseif ($paramDate == 3) {
                $startDate = date('Y-m-d', mktime(0, 0, 0, date("m"), 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(23, 59, 59, date('m'), date('t'), date('Y')) - 1) . ' 23:59:59';

            } elseif ($paramDate == 4) {
                $getMonthDays = date("t", mktime(0, 0, 0, date('n') + (date('n') - 1) % 3, 1, date("Y")));//本季度未最后一月天数

                $startDate = date('Y-m-d H:i:s', mktime(0, 0, 0, date('n') - (date('n') - 1) % 3, 1, date('Y')));
                $endDate = date('Y-m-d H:i:s', mktime(23, 59, 59, date('n') + (date('n') - 1) % 3, $getMonthDays, date('Y')));

            } elseif ($paramDate == 5) {
                $startDate = date('Y-m-d', mktime(0, 0, 0, 1, 1, date("Y"))) . ' 00:00:00';
                $endDate = date('Y-m-d', mktime(0, 0, 0, 1, 1, date("Y") + 1) - 1) . ' 23:59:59';
            } else {
                //开始时间
                $startDate = $request->param('start_date');
                //结束时间
                $endDate = $request->param('end_date');
            }

            //1不处理 2本周 3当月  5本年
            if ($paramDate == 2) {
                $result = $this->weekDetails($startDate, $endDate, $idArr, $cerIdArr);
            } elseif ($paramDate == 3) {
                $result = $this->index2Moon(date('m'), $idArr, $cerIdArr);
            } elseif ($paramDate == 5) {
                $result = $this->trend($idArr, $cerIdArr);
            } else {
                $result = $this->getErleizoushituDay($startDate, $endDate, $idArr, $cerIdArr);
            }
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }

    /**
     * 二类走势图区间每一天数据
     */

    public function getErleizoushituDay($startDate, $endDate, $idArr, $cerIdArr)
    {

        $start = new DateTime($startDate);
        $interval = new DateInterval('P1D');
        $end = new DateTime($endDate);
        $recurrences = 4;
//        $iso = 'R4/2012-07-01T00:00:00Z/P7D';

        $dates = new DatePeriod($start, $interval, $recurrences);
        /** @var TYPE_NAME $period */
        $dates = new DatePeriod($start, $interval, $end);


        // 遍历每一天，将其所在的周存入数组
        $result = [];
        foreach ($dates as $k => $date) {
            $result[$k]['title'] = $date->format('Y-m-d');
            $result[$k]['total'] = round($this->getTotal($date->format('Y-m-d') . ' 00:00:00', $date->format('Y-m-d') . ' 23:59:58', $idArr, $cerIdArr), 3);
        }
        return $result;
    }

    /**
     * Ⅱ类业绩概况（公司--部门--人员） 月度 目标&业绩
     */
    public function getTwoTypeCompany(Request $request, User $user, SystemTargetLib $targetLib, System $system, UserOrganization $organization)
    {
        $keyWord = $request->get('keyword');
        $id = $request->get('oid') ?: 1; //公司id
        $export = $request->get('export') ?: 0; //导出标示 1导出

        if ($keyWord == 1) {
            //二类证书id
            $cerId = $this->erleiCertificate_id;

            //查询当月 开始时间&结束时间
            $date = date('Y-m-1');
            $dateEnd = date('Y-m-t', strtotime($date));

            $type = $request->get('type');//1查询公司  2查询部门  3查询个人

            if ($type == 1) {
                /**
                 * 查询公司 查询用户表所有公司合集
                 */
                $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0]);
//               $orgStr = $system->getOrgIdStr($id,$organization->getStructureArrDataModel());
//               $comId = $organization->getOrgInNameModel($orgStr);
                $comId = $user->getGroupCompany();

                //查询每个公司月对应的目标业绩
                foreach ($comId as $k => $item) {
                    if (!empty($item['company_id']['id'])) {
                        $result['data'][$k]['id'] = $item['company_id']['id'];
                        $result['data'][$k]['text'] = $item['company_id']['text'];
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($date, $item['company_id']['id'], 2) ?: 0;
                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                }
            }
            if ($type == 2) {
                /**
                 * 查询部门 查询用户表所有公司合集
                 */
                $idArr = '';
//               $orgId = $user->getGroupOrgModel();
                $orgStr = $system->getOrgIdStr($id, $organization->getStructureArrDataModel());
                $orgId = $organization->getOrgInNameModel($orgStr);

                //查询每个公司月对应的目标业绩
                foreach ($orgId as $k => $item) {

                    if (!empty($item['id'])) {

                        //查询部门下对应的人员ID
                        $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0, 'department_id' => $item['id']]);

                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['title'];
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($date, $item['id'], 2) ?: 0;
                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);

                        unset($idArr);
                    }
                }
                //通过id查询oname
                $oname = $organization->getStructureName($id);
                //给前段添加type name
                $result['param']['type'] = $type;
                $result['param']['name'] = $oname;
                $result['param']['oid'] = $id;

            }
            if ($type == 3) {
                /**
                 * 查询个人
                 */
                $idArr = '';
                $userId = $user->getOrgUidModel($id);

                //查询每个公司月对应的目标业绩
                foreach ($userId as $k => $item) {
                    $idArr = $item['id'];
                    if (!empty($item['id'])) {
                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['nickname'];
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($date, $item['id'], 1) ?: 0;

                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                    unset($idArr);
                }

                //通过id查询oname
                $oname = $organization->getStructureName($id);
                //给前段添加type name
                $result['param']['type'] = $type;
                $result['param']['name'] = $oname;
                $result['param']['oid'] = $id;
            }
        } else {
            //二类证书id
            $cerId = $this->erleiCertificate_id;

            //查询当月 开始时间&结束时间
            $date = date('Y-m-1');
            $dateEnd = date('Y-m-t', strtotime($date));
            $id = $request->get('oid') ?: 1; //公司id
            $type = $request->get('type');//1查询公司  2查询部门  3查询个人

            //查询本月有几周
            $weekNum = get_weekinfo($date);

            if ($type == 1) {
                /**
                 * 查询公司 查询用户表所有公司合集
                 */
                //数据范围
                $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0]);
                //公司列表
                $comId = $user->getGroupCompany();


                //查询每个公司周对应的实际业绩
                foreach ($comId as $k => $item) {
                    if (!empty($item['company_id']['id'])) {
                        $result['data'][$k]['id'] = $item['company_id']['id'];
                        $result['data'][$k]['text'] = $item['company_id']['text'];
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                }
            }
            if ($type == 2) {
                /**
                 * 查询部门 查询用户表所有公司合集
                 */
                $idArr = '';

                $orgStr = $system->getOrgIdStr($id, $organization->getStructureArrDataModel());
                $orgId = $organization->getOrgInNameModel($orgStr);

                //查询每个公司月对应的目标业绩
                foreach ($orgId as $k => $item) {
                    if (!empty($item['id'])) {
                        //查询部门下对应的人员ID
                        $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0, 'department_id' => $item['id']]);

                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['title'];
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                }
                //通过id查询oname
                $oname = $organization->getStructureName($id);
                //给前段添加type name
                $result['param']['type'] = $type;
                $result['param']['name'] = $oname;
                $result['param']['oid'] = $id;

            }
            if ($type == 3) {
                /**
                 * 查询个人
                 */
                $idArr = '';
                $userId = $user->getOrgUidModel($id);

                //查询每个公司月对应的目标业绩
                foreach ($userId as $k => $item) {
                    $idArr = $item['id'];

                    if (!empty($item['id'])) {
                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['nickname'];
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                    unset($idArr);
                }
                //通过id查询oname
                $oname = $organization->getStructureName($id);
                //给前段添加type name
                $result['param']['type'] = $type;
                $result['param']['name'] = $oname;
                $result['param']['oid'] = $id;
            }
        }
        if ($export == 1) {
            $this->exportMode($result, $keyWord);
        }
        if (isset($result['data'])) {
            $result['data'] = array_values($result['data']);
        } else {
            $result['data'] = [];
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    /**
     * Ⅱ类业绩概况（公司--部门--人员） 周 目标&业绩
     */
    public function getTwoTypeWeek(Request $request, User $user)
    {
        //二类证书id
        $cerId = $this->erleiCertificate_id;

        //查询当月 开始时间&结束时间
        $date = date('Y-m-1');
        $dateEnd = date('Y-m-t', strtotime($date));

        $type = $request->get('type');//1查询公司  2查询部门  3查询个人

        //查询本月有几周
        $weekNum = get_weekinfo($date);
        $result = [];
        if ($type == 1) {
            /**
             * 查询公司 查询用户表所有公司合集
             */

            //数据范围
            $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0]);
            //公司列表
            $comId = $user->getGroupCompany();


            //查询每个公司周对应的实际业绩
            foreach ($comId as $k => $item) {
                if (!empty($item['company_id']['id'])) {
                    $result[$k]['id'] = $item['company_id']['id'];
                    $result[$k]['text'] = $item['company_id']['text'];
                    //实际业绩
                    foreach ($weekNum as $ks => $weekItem) {
                        $result[$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                    }
                }
            }
        }
        if ($type == 2) {
            /**
             * 查询部门 查询用户表所有公司合集
             */
            $idArr = '';

            $orgId = $user->getGroupOrgModel();

            //查询每个公司月对应的目标业绩
            foreach ($orgId as $k => $item) {
                if (!empty($item['department_id']['id'])) {

                    //查询部门下对应的人员ID
                    $idArr = $user->getFIdResult(['type' => 0, 'is_k' => 0, 'department_id' => $item['department_id']['id']]);

                    $result[$k]['id'] = $item['department_id']['id'];
                    $result[$k]['text'] = $item['department_id']['text'];
                    //实际业绩
                    foreach ($weekNum as $ks => $weekItem) {
                        $result[$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                    }
                }
            }
        }
        if ($type == 3) {
            /**
             * 查询个人
             */
            $idArr = '';
            $userId = $user->getGroupUidModel();

            //查询每个公司月对应的目标业绩
            foreach ($userId as $k => $item) {
                $idArr = $item['id'];

                if (!empty($item['id'])) {
                    $result[$k]['id'] = $item['id'];
                    $result[$k]['text'] = $item['nickname'];
                    //实际业绩
                    foreach ($weekNum as $ks => $weekItem) {
                        $result[$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                    }
                }
                unset($idArr);
            }
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);

    }


    /**
     * Ⅱ类业绩概况（公司--部门--人员） 月度 目标&业绩
     */
    public function getTwoTypeCompanys(
        Request          $request,
        User             $user,
        SystemTargetLib  $targetLib,
        System           $system,
        UserOrganization $organization,
        Power $power
    ){
        $keyWord = $request->get('keyword');
        $id = $request->get('oid') ?: ''; //公司id
        $export = $request->get('exports') ?: 0; //导出标示 1导出
        $param = $request->get();
        $uid = $request->get ('user_login_id');

        //所有公司合集
        $comData = $organization->getStructure();
        //二类证书id
        $cerId = $this->erleiCertificate_id;

        //获取当前用户数据可见范围
        $userRand = $power->getUserDataRand($uid);

        //获取当前用户部门
        $userOrgId = $user->getUidOrgId($uid);

        //查询当月 开始时间&结束时间
//        $date = date('Y-m-1').' 00:00:00';
//        $dateEnd = date('Y-m-t', strtotime ($date)).' 23:59:59';
//        $date = "2023-10-1";
//        $dateEnd = date('Y-m-t', strtotime ($date)).' 23:59:59';

        if (!empty($param['start_date']) && !empty($param['end_date'])) {
            $date = $param['start_date'] . ' 00:00:00';
            $dateEnd = $param['end_date'] . ' 23:59:59';
        } else {
            //默认当天
            $date = date('Y-m-d') . ' 00:00:00';
            $dateEnd = date('Y-m-d', strtotime($date)) . ' 23:59:59';
        }

        $dateLib = date('Y-m-1') . ' 00:00:00';
        $result = [];
        if ($keyWord == 1) {

            /**
             * 查询总公司
             */

            if ($userRand === 1){
                if (empty($id)) {
                    $comId = $organization->getCompanyTypeData();
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }

                if (empty($comId)) { //如果部门下级为空 查询该部门人员

                    $userId = $user->getOrgUidModel($id);
                    //查询每个人对应的月目标业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];
                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //目标业绩
                            $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 1) ?: 0;

                            //实际业绩
                            $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                        }
                        unset($idArr);
                    }
                } else {
                    //查询每个公司月对应的目标业绩
                    foreach ($comId as $k => $item) {
                        //查询公司下面所有部门
                        $oidArr = rtrim($system->getOrgIdStr($item['id'], $comData), ',');

                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 2) ?: 0;

                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                }
            }else if($userRand === 2){
                if (empty($id)) {
                    $comId = $organization->getOrgInNameModel($system->getOrgFgsId($userOrgId));
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }

                if (empty($comId)) { //如果部门下级为空 查询该部门人员

                    $userId = $user->getOrgUidModel($id);
                    //查询每个人对应的月目标业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];
                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //目标业绩
                            $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 1) ?: 0;

                            //实际业绩
                            $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                        }
                        unset($idArr);
                    }
                } else {
                    //查询每个公司月对应的目标业绩
                    foreach ($comId as $k => $item) {
                        //查询公司下面所有部门
                        $oidArr = rtrim($system->getOrgIdStr($item['id'], $comData), ',');

                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 2) ?: 0;

                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                }

            }else if($userRand === 3){
                if (empty($id)) {
                    $comId = $organization->getOrgInNameModel($userOrgId);
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }

                if (empty($comId)) { //如果部门下级为空 查询该部门人员

                    $userId = $user->getOrgUidModel($id);
                    //查询每个人对应的月目标业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];
                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //目标业绩
                            $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 1) ?: 0;

                            //实际业绩
                            $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                        }
                        unset($idArr);
                    }
                } else {
                    //查询每个公司月对应的目标业绩
                    foreach ($comId as $k => $item) {
                        //查询公司下面所有部门
                        $oidArr = rtrim($system->getOrgIdStr($item['id'], $comData), ',');

                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 2) ?: 0;

                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                }
            }else{
                $userId = [$user->getIdUserData ($uid)];
                //查询每个人对应的月目标业绩
                foreach ($userId as $k => $item) {
                    $idArr = $item['id'];
                    if (!empty($item['id'])) {
                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['nickname'];
                        $result['data'][$k]['type'] = 1;//人员
                        //目标业绩
                        $result['data'][$k]['target_performance'] = $targetLib->getValueTargetModel($dateLib, $item['id'], 1) ?: 0;

                        //实际业绩
                        $result['data'][$k]['actual_performance'] = $this->getTotal($date, $dateEnd, $idArr, $cerId);
                    }
                    unset($idArr);
                }
            }
        } else {
            $id = $request->get('oid') ?: ""; //公司id
            $date = date('Y-m-1') . ' 00:00:00';
            //查询本月有几周
            $weekNum = get_weekinfo($date);

            /**
             * 查询公司
             */

            if($userRand == 1){
                if (empty($id)) {
                    $comId = $organization->getCompanyTypeData();
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }

                if (empty($comId)) {
                    $userId = $user->getOrgUidModel($id);

                    //查询每个人对应的业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];

                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //实际业绩
                            foreach ($weekNum as $ks => $weekItem) {
                                $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                            }
                        }
                        unset($idArr);
                    }

                } else {
                    foreach ($comId as $k => $val) {
                        //查询公司下面所有部门
                        $oidArr = $system->getOrgIdStr($val['id'], $comData);
                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $val['id'];
                        $result['data'][$k]['text'] = $val['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                }

            }else if($userRand == 2){
                if (empty($id)) {
                    $comId = $organization->getOrgInNameModel($system->getOrgFgsId($userOrgId));
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }

                if (empty($comId)) {
                    $userId = $user->getOrgUidModel($id);

                    //查询每个人对应的业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];

                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //实际业绩
                            foreach ($weekNum as $ks => $weekItem) {
                                $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                            }
                        }
                        unset($idArr);
                    }

                } else {
                    foreach ($comId as $k => $val) {
                        //查询公司下面所有部门
                        $oidArr = $system->getOrgIdStr($val['id'], $comData);
                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $val['id'];
                        $result['data'][$k]['text'] = $val['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                }
            }else if($userRand == 3){
                if (empty($id)) {
                    $comId = $organization->getOrgInNameModel($userOrgId);
                } else {
                    $comId = $organization->getCompanyTypeData($id);
                }
                if (empty($comId)) {
                    $userId = $user->getOrgUidModel($id);

                    //查询每个人对应的业绩
                    foreach ($userId as $k => $item) {
                        $idArr = $item['id'];

                        if (!empty($item['id'])) {
                            $result['data'][$k]['id'] = $item['id'];
                            $result['data'][$k]['text'] = $item['nickname'];
                            $result['data'][$k]['type'] = 1;//人员
                            //实际业绩
                            foreach ($weekNum as $ks => $weekItem) {
                                $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                            }
                        }
                        unset($idArr);
                    }

                } else {
                    foreach ($comId as $k => $val) {
                        //查询公司下面所有部门
                        $oidArr = $system->getOrgIdStr($val['id'], $comData);
                        //查询所有属于公司的id
                        $idArr = $user->getOidUidDataModel($oidArr);

                        $result['data'][$k]['id'] = $val['id'];
                        $result['data'][$k]['text'] = $val['title'];
                        $result['data'][$k]['type'] = 0;//部门
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                }

            }else{
                $userId = [$user->getIdUserData ($uid)];

                //查询每个人对应的业绩
                foreach ($userId as $k => $item) {
                    $idArr = $item['id'];

                    if (!empty($item['id'])) {
                        $result['data'][$k]['id'] = $item['id'];
                        $result['data'][$k]['text'] = $item['nickname'];
                        $result['data'][$k]['type'] = 1;//人员
                        //实际业绩
                        foreach ($weekNum as $ks => $weekItem) {
                            $result['data'][$k][weekCapitalization($ks)] = $this->getTotal($weekItem['start'], $weekItem['end'], $idArr, $cerId);
                        }
                    }
                    unset($idArr);
                }
            }

        }
        if ($export == 1) {
            $this->exportMode($result, $keyWord);
        }

        if (isset($result['data'])) {
            $result['data'] = array_values($result['data']);
        } else {
            $result['data'] = [];
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $result);
    }


    /**
     * 首页目标设置
     */
    public function setTarget(Request $request, SystemTargetLib $target)
    {
        $uid = $request->post('user_login_id');
        //通过用户id查询当前用户数据可见范围是否是管理员
        $date = $request->post('moon_date') . '-1';

        $param = $request->post('array');
//        Log::error($date);
        //个人目标与组织目标
        foreach ($param as $value) {
//            $value['uid'] = $uid;
//            if (empty($value['type'])) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);
            $value['moon_date'] = $date;
            //target_lib 转json入库
            $value['target_lib'] = json_encode($value['target_lib']);
            $target->editWhereIdTypeModel($date, $value['uid'], $value['type'], $value);
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SETTING);

    }

    /**
     * 获取用户设置目标
     */

    public function getTarget(Request $request, Power $power, SystemTargetLib $target, UserOrganization $organization, User $user, System $systemService)
    {
        $uid = $request->get('user_login_id');

        $date = $request->get('date');

        //获取这个月有几周
        $moon = weekOfMonth(strtotime($date));

        $moon_day = $target->getValueTargetDayModel(date('Y-m-1',strtotime ($date)),'',3,3);
        //查询用户基础数据
        $userFindData = $user->getIdUserData($uid);

        //通过用户id查询当前用户数据可见范围是否是管理员
        $type = $power->getUserDataRand($uid); //type 小于等于3 就是管理员   1总公司  2分公司 3部门  4个人

        //查看公司目标
        $com = [];
        if ($type == 1) {//总公司权限
            if ($userFindData['username'] === 'admin') {
                $com['uid'] = $organization->getZgsId();
            } else {
                $com['uid'] = $systemService->getOrgZgsId($userFindData['department_id']['id']);
            }

            //获取当前部门所在的总公司
            $com['name'] = $organization->getStructureName($systemService->getOrgZgsId($com['uid'])) ?: '';
            $com['uid'] = $systemService->getOrgZgsId($com['uid']);
//            $com['name'] = $organization->getStructureName ($com['uid'])?:'';
            $com['moon_day'] = $moon_day;
            $com['moon_target'] = $target->getOrgMoonDataModel($date, $com['uid'], 'moon_target') ?: '';

            $com['type'] = 2;
            $com['day'] = $moon;
            //获取是否已经设置目标
            $com['target_lib'] = $target->getOrgMoonJsonDataModel($date, $com['uid'], 2);
//            for ($i = 0; $i < $moon; $i++) {

//                $com['circ_'.numberToLetter($i).'_week_day'] = $target->getOrgMoonDataModel($date,$userFindData['company_id'],'circ_'.numberToLetter($i).'_week_day')?:'';
//                $com['circ_'.numberToLetter($i).'_target'] = $target->getOrgMoonDataModel($date,$userFindData['company_id'],'circ_'.numberToLetter($i).'_target')?:'';
//            }
        }

        if ($type == 2) {
            //分公司权限 根据用户基础数据公司id查询对应目标内容
            if (is_array($userFindData['department_id'])) {
                $com['uid'] = $userFindData['department_id']['id'];
            } else {
                $com['uid'] = $userFindData['department_id'];
            }

            //分公司权限 根据用户基础数据公司id查询对应目标内容
            $com['name'] = $organization->getStructureName($systemService->getOrgFgsId($com['uid'])) ?: '';
            $com['uid'] = $systemService->getOrgFgsId($com['uid']);

            $com['type'] = 2;
            $com['moon_day'] = $moon_day;
            $com['moon_target'] = $target->getOrgMoonDataModel($date, $com['uid'], 'moon_target') ?: '';
            $com['day'] = $moon;
            //获取是否已经设置目标
            $com['target_lib'] = $target->getOrgMoonJsonDataModel($date, $com['uid'], 2);
//            for ($i = 0; $i < $moon; $i++) {
//                $com['circ_'.numberToLetter($i).'_week_day'] = $target->getOrgMoonDataModel($date,$userFindData['company_id'],'circ_'.numberToLetter($i).'_week_day')?:'';
//                $com['circ_'.numberToLetter($i).'_target'] = $target->getOrgMoonDataModel($date,$userFindData['company_id'],'circ_'.numberToLetter($i).'_target')?:'';
//            }
        }

        if ($type == 3) {
            //部门权限 根据用户基础数据部门查询对应目标内容
            if (is_array($userFindData['department_id'])) {
                $com['uid'] = $userFindData['department_id']['id'];
            } else {
                $com['uid'] = $userFindData['department_id'];
            }
            //总公司权限 根据用户基础数据公司id查询对应目标内容
            $com['name'] = $organization->getStructureName($com['uid']) ?: '';
            $com['type'] = 2;
            $com['moon_day'] = $moon_day;
            $com['moon_target'] = $target->getOrgMoonDataModel($date, $com['uid'], 'moon_target') ?: '';
            $com['day'] = $moon;
            //获取是否已经设置目标
            $com['target_lib'] = $target->getOrgMoonJsonDataModel($date, $com['uid'], 2);
//            for ($i = 0; $i < $moon; $i++) {
//                $com['circ_'.numberToLetter($i).'_week_day'] = $target->getOrgMoonDataModel($date,$userFindData['department_id'],'circ_'.numberToLetter($i).'_week_day')?:'';
//                $com['circ_'.numberToLetter($i).'_target'] = $target->getOrgMoonDataModel($date,$userFindData['department_id'],'circ_'.numberToLetter($i).'_target')?:'';
//            }
        }
        //个人目标
        $people['name'] = $user->getIdNickName($userFindData['id']) ?: '';
        $people['moon_day'] = $moon_day;
        $people['moon_target'] = $target->getUidMoonDataModel($date, $uid, 'moon_target') ?: '';
        $people['uid'] = $uid;
        $people['type'] = 1;
        $people['day'] = $moon;
        //获取是否已经设置目标
        $people['target_lib'] = $target->getOrgMoonJsonDataModel($date, $uid, 1);
//        for ($i = 0; $i < $moon; $i++) {
//            $people['circ_'.numberToLetter($i).'_week_day'] = $target->getUidMoonDataModel($date,$uid,'circ_'.numberToLetter($i).'_week_day')?:'';
//            $people['circ_'.numberToLetter($i).'_target'] = $target->getUidMoonDataModel($date,$uid,'circ_'.numberToLetter($i).'_target')?:'';
//        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            ['people' => (object)$people],
            ['company' => (object)$com]
        ]);

    }

    /**
     * 获取用户设置周目标
     */
    public function getCircumferenceTarget(
        Request          $request,
        SystemTargetLib  $targetLibModel,
        UserOrganization $organization,
        User             $user,
        System           $systemService,
        Power            $power
    ){
        $uid = $request->get('user_login_id');
        $date = time();
        //每周起止时间
        $weekDate = get_weekinfo(date('Y-m'));
        $whereDate = '';
        foreach ($weekDate as $item) {
            if (strtotime($item['start']) <= $date && $date <= strtotime($item['end'])) {
                $whereDate = $item['start'];
                break;
            }
        }

        //查询用户基础数据
        $userFindData = $user->getIdUserData($uid);

        //通过用户id查询当前用户数据可见范围是否是管理员
        $type = $power->getUserDataRand($uid); //type 小于等于3 就是管理员   1总公司  2分公司 3部门  4个人

        //查看公司目标
        $com = [];
        if ($type == 1) {//总公司权限
            if ($userFindData['username'] === 'admin') {
                $com['uid'] = $organization->getZgsId();
            } else {
                $com['uid'] = $systemService->getOrgZgsId($userFindData['department_id']['id']);
            }

            //获取当前部门所在的总公司
            $com['name'] = $organization->getStructureName($systemService->getOrgZgsId($com['uid'])) ?: '';
            $com['uid'] = $systemService->getOrgZgsId($com['uid']);
//            $com['name'] = $organization->getStructureName ($com['uid'])?:'';
            $com['moon_day'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_day', 2) ?: '';
            $com['moon_target'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_target', 2) ?: '';

            $com['type'] = 2;
            //获取是否已经设置目标
            $com['target_lib'] = $targetLibModel->getOrgWeekJsonDataModel($whereDate, $com['uid'], 2, 2);
        }

        if ($type == 2) {
            //分公司权限 根据用户基础数据公司id查询对应目标内容
            if (is_array($userFindData['department_id'])) {
                $com['uid'] = $userFindData['department_id']['id'];
            } else {
                $com['uid'] = $userFindData['department_id'];
            }

            //分公司权限 根据用户基础数据公司id查询对应目标内容
            $com['name'] = $organization->getStructureName($systemService->getOrgFgsId($com['uid'])) ?: '';
            $com['uid'] = $systemService->getOrgFgsId($com['uid']);

            $com['type'] = 2;
            $com['moon_day'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_day', 2) ?: '';
            $com['moon_target'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_target', 2) ?: '';
            //获取是否已经设置目标
            $com['target_lib'] = $targetLibModel->getOrgWeekJsonDataModel($whereDate, $com['uid'], 2, 2);
        }

        if ($type == 3) {

            //部门权限 根据用户基础数据部门查询对应目标内容
            if (is_array($userFindData['department_id'])) {
                $com['uid'] = $userFindData['department_id']['id'];
            } else {
                $com['uid'] = $userFindData['department_id'];
            }

            //总公司权限 根据用户基础数据公司id查询对应目标内容
            $com['name'] = $organization->getStructureName($com['uid']) ?: '';
            $com['type'] = 2;

            $com['moon_day'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_day', 2) ?: '';

            $com['moon_target'] = $targetLibModel->getOrgWeekDataModel($whereDate, $com['uid'], 'moon_target', 2) ?: '';

            //获取是否已经设置目标
            $com['target_lib'] = $targetLibModel->getOrgWeekJsonDataModel($whereDate, $com['uid'], 2, 2);
        }

        //个人目标
        $people['name'] = $user->getIdNickName($userFindData['id']) ?: '';

        $people['moon_day'] = $targetLibModel->getUidWeekDataModel($whereDate, $uid, 'moon_day', 2) ?: '';
        $people['moon_target'] = $targetLibModel->getUidWeekDataModel($whereDate, $uid, 'moon_target', 2) ?: '';
        $people['uid'] = $uid;
        $people['type'] = 1;
        //获取是否已经设置目标
        $people['target_lib'] = $targetLibModel->getOrgWeekJsonDataModel($whereDate, $uid, 1, 2);

        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, [
            ['people' => (object)$people],
            ['company' => (object)$com]
        ]);
    }

    /**
     * 设置周目标
     */
    public function setCircumferenceTarget(Request $request, Power $power, SystemTargetLib $target, UserOrganization $organization, User $user, System $systemService)
    {
        $uid = $request->get('user_login_id');
        $date = time();
        //每周起止时间
        $weekDate = get_weekinfo(date('Y-m'));
        $whereDate = '';
        foreach ($weekDate as $item) {
            if (strtotime($item['start']) <= $date && $date <= strtotime($item['end'])) {
                $whereDate = $item['start'];
                break;
            }
        }

        $param = $request->post('array');

        //个人目标与组织目标
        foreach ($param as $value) {

            $value['moon_date'] = $whereDate;
            //target_lib 转json入库
            $value['target_lib'] = json_encode($value['target_lib']);
            $value['week_type'] = 2;
            $target->editWhereIdTypeModel($whereDate, $value['uid'], $value['type'], $value, 2);
        }

        return ReJson(message::$SUCC_CODE, message::$SUCC_SETTING);
    }

    /**
     * 二类业绩年走势图
     * @param \app\Request $request
     * @param \app\model\OrderEnterpriseCompany $company
     * @param \app\model\OrderEnterpriseExchange $exchange
     * @param \app\model\OrderEnterpriseCertificateBusiness $business
     * @param \app\model\OrderOtherCertificateBusiness $other
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    public function trend($idArr, $cerIdArr)
    {
        $moon = 12;
        for ($i = 1; $i <= $moon; $i++) {
            $moonStart = date('Y-') . $i . '-1 00:00:00';

            $moonEnd = $this->twelvemonth($moonStart).' 23:59:59';

            //总业绩
            $result[$i]['total'] = round($this->getTotal($moonStart, $moonEnd, $idArr, $cerIdArr), 2);
            //键
            $result[$i]['title'] = '第' . intCapitalization($i) . '月';
        }

        return array_values ($result);
    }

    /**
     * 二类业绩月走势图
     * @param $moon
     * @param $idArr
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index2Moon($moon, $idArr, $cerIdArr)
    {
        /**
         * 第一周
         */

        $moonStart = date('Y-') . $moon . '-1';
        //判断给定日期是周几
        $dateW = date('w', strtotime($moonStart));
        $moonEnd = date('Y-') . $moon . '-' . (8 - $dateW);

        //总业绩
        $result[0]['total'] = round($this->getTotal($moonStart, $moonEnd, $idArr, $cerIdArr), 3);
        $result[0]['title'] = '第一周';
        //周内业绩详情
//        $result[0]['week'] = $this->weekDetails($moonStart,$moonEnd,$idArr,$dateW);


        /**
         * 第二周
         */
        $moonStart2 = date('Y-') . $moon . '-' . (date('d', strtotime($moonEnd)) + 1);

        $moonEnd2 = date('Y-') . $moon . '-' . (date('d', strtotime($moonStart2)) + 6);

        $result[1]['total'] = round($this->getTotal($moonStart2, $moonEnd2, $idArr, $cerIdArr), 3);
        $result[1]['title'] = '第二周';
        //周内业绩详情
//        $result[1]['week'] = $this->weekDetails($moonStart2,$moonEnd2,$idArr);

        /**
         * 第三周
         */
        $moonStart3 = date('Y-') . $moon . '-' . (date('d', strtotime($moonEnd2)) + 1);

        $moonEnd3 = date('Y-') . $moon . '-' . (date('d', strtotime($moonStart3)) + 6);
        $result[2]['total'] = round($this->getTotal($moonStart3, $moonEnd3, $idArr, $cerIdArr), 3);
        $result[2]['title'] = '第三周';

        //周内业绩详情
//        $result[2]['week'] = $this->weekDetails($moonStart3,$moonEnd3,$idArr);

        /**
         * 第四周
         */
        $moonStart4 = date('Y-') . $moon . '-' . (date('d', strtotime($moonEnd3)) + 1);

        $moonEnd4 = date('Y-') . $moon . '-' . (date('d', strtotime($moonStart4)) + 6);

        $result[3]['total'] = round($this->getTotal($moonStart4, $moonEnd4, $idArr, $cerIdArr), 3);
        $result[3]['title'] = '第四周';

        //周内业绩详情
//        $result[3]['week'] = $this->weekDetails($moonStart4,$moonEnd4,$idArr);

        /**
         * 第五周
         */
        //判断是否有第五周
        $lastday = date('Y-m-d', strtotime("$moonStart +1 month -1 day"));

        $day = (strtotime($lastday) - strtotime($moonEnd4)) / 86400;

        if ($day > 7) $day = 7;

        if ($day > 0) {
            $moonStart5 = date('Y-') . $moon . '-' . (date('d', strtotime($moonEnd4)) + 1);

            $moonEnd5 = date('Y-') . $moon . '-' . (date('d', strtotime($moonStart5)) + $day - 1);

            $result[4]['total'] = round($this->getTotal($moonStart5, $moonEnd5, $idArr, $cerIdArr), 3);
            $result[4]['title'] = '第五周';

//            $result[4]['week'] = $this->weekDetails($moonStart5,$moonEnd5,$idArr);
        }

        /**
         * 第六周
         */

        $days = (strtotime($lastday) - strtotime($moonEnd5)) / 86400;

        if ($days > 0) {
            $moonStart6 = date('Y-') . $moon . '-' . (date('d', strtotime($moonEnd5)) + 1);

            $moonEnd6 = date('Y-') . $moon . '-' . (date('d', strtotime($moonStart6)) + $days - 1);

            $result[5]['total'] = round($this->getTotal($moonStart6, $moonEnd6, $idArr, $cerIdArr), 3);
            $result[5]['title'] = '第六周';

//            $result[5]['week'] = $this->weekDetails($moonStart6,$moonEnd6,$idArr);
        }

        return $result;
    }

    /**
     * 查询周内数据详情
     * @param \app\Request $request
     * @param \app\model\User $user
     * @return false|string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */

    //获取周内数据
    public function getWeekData(Request $request, User $user,Power $power)
    {
        //登陆人ID
        $uid = $request->get ('user_login_id');
        //用户ID
        $id = $request->get('id');
        $export = $request->get('export') ?: 0;

        //获取当前用户数据可见范围
        $userRand = $power->getUserDataRand($uid);

        //查询该用户所属部门
        $orgId = $user->getUidOrgId($id);
        $cerId = $this->erleiCertificate_id;

        //周几weekNum
        $weekNum = $request->get('weekNum');
        $Wnum = weekCapitalizationKey($weekNum);
        //查询部门人员列表
        if ($userRand == 4){
            $userData = [$user->getIdUserData ($id)];
        }else{
            $userData = $user->getOrgUserFieldModel($orgId);
        }

        //查询本月第几周起止时间

        //本周开始时间，结束时间
        $weekArr = getWeekDetails($Wnum);

        //给每一天赋值
        foreach ($userData as &$userDatum) {
            $day = 1;
            $totalPerformance = 0;//总业绩
            for ($i = 6; $i >= 0; $i--) {

                $strTime = date('Y-m-d', strtotime($weekArr['end']) - 86400 * ($day - 1)) . ' 00:00:00';
                $endTime = date('Y-m-d', strtotime($weekArr['end']) - 86400 * ($day - 1)) . ' 23:59:59';
                //判断时间是否小于开始时间
//                print_r ($strTime);
//                echo "------";
//                print_r ($endTime);
//                echo PHP_EOL;
                $w = date('w', strtotime($strTime));

                if (strtotime($weekArr['start']) > strtotime($strTime)) {
                    $userDatum[week($w)] = 0;
                } else {
                    $userDatum[week($w)] = $this->getTotal($strTime, $endTime, $userDatum['id'], $cerId);

                }

                $totalPerformance += $userDatum[week($w)]; //计算总业绩
                $day++;
            }
            $userDatum['total_performance'] = $totalPerformance;
        }

        if ($export) {
            //导出
            $this->WeekExport($userData);
            die;
        }
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $userData);
    }

    /**
     * II类业绩概括 人员详情导出
     */
    public function WeekExport($result)
    {
        $orgModel = new UserOrganization();
        $systemService = new System();
        $userModel = new User();
        //拼接完成部门
        foreach ($result as &$item) {
            if ($item['nickname']) {
                if ($userModel->getOrgIdModel($item['nickname'])) {
                    $item['nickname'] = $systemService->getOrgStrName($userModel->getOrgIdModel($item['nickname'])) . '/' . $item['nickname'];
                }
            }
        }

        $excel = new Excel();

        $data = [
            ['s_cell' => 'nickname', 's_value' => '姓名', 's_width' => 10],
            ['s_cell' => 'monday', 's_value' => '星期一', 's_width' => 10],
            ['s_cell' => 'tuesday', 's_value' => '星期二', 's_width' => 10],
            ['s_cell' => 'wednesday', 's_value' => '星期三', 's_width' => 10],
            ['s_cell' => 'thursday', 's_value' => '星期四', 's_width' => 10],
            ['s_cell' => 'friday', 's_value' => '星期五', 's_width' => 10],
            ['s_cell' => 'saturday', 's_value' => '星期六', 's_width' => 10],
            ['s_cell' => 'weekend', 's_value' => '星期日', 's_width' => 10],
            ['s_cell' => 'total_performance', 's_value' => '总计', 's_width' => 10],
        ];
        $excel->outExcelStart($result, $data, 'Ⅱ类业绩导出');
    }

    public function weekDetails($moonStart, $moonEnd, $uidArr, $cerIdArr, $dateW = 1): array
    {

        $weekData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        //周内业绩详情
        $count = (strtotime($moonEnd) - strtotime($moonStart)) / 86400;

        $data = [];
        for ($i = 0; $i <= $count; $i++) {

            $forStart = date('Y-m-d,H:i:s', strtotime($moonStart) + 86400 * $i);
            $forEnd = date('Y-m-d,H:i:s', strtotime($forStart) + 86399);
//            $data[$weekData[($i+$dateW-1)]] = round($this->getTotal($forStart,$forEnd,$uidArr),3);
            $data[$i]['total'] = round($this->getTotal($forStart, $forEnd, $uidArr, $cerIdArr), 3);
            $data[$i]['title'] = $weekData[($i + $dateW - 1)];
        }
        return $data;
    }


    public function twelvemonth($date)
    {
        $first = date('Y-m-01', strtotime($date));
        return date('Y-m-d', strtotime("$first +1 month -1 day"));
    }

    /**
     * 获取总业绩
     * @param $moonStart
     * @param $moonEnd
     * @param $uidArr
     * @param string $cerType
     * @return float|int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTotal($moonStart, $moonEnd, $uidArr, $cerType = '')
    {

        $company = new OrderEnterpriseCompany();
        $exchange = new OrderEnterpriseExchange();
        $other = new OrderOtherCertificateBusiness();
        $business = new OrderEnterpriseCertificateBusiness();
        $orderDealChargebackModel = new OrderDealChargeback();
        $certificateModel = new SystemCertificate();

        //企业证书注册
        $enterData = $company->getSummary($moonStart, $moonEnd, $uidArr, $cerType);
        //企业倒证
        $exchangeData = $exchange->getSummaryModel($moonStart, $moonEnd, $uidArr, $cerType);
        //证书办理
        $otherData = $other->getSummaryModel($moonStart, $moonEnd, $uidArr, $cerType);
        //企业证书
        $businessData = $business->getSummaryModel($moonStart, $moonEnd, $uidArr);
//print_r ($enterData);
//echo PHP_EOL;
//echo '--------';
//print_r ($exchangeData);
//echo PHP_EOL;
//echo ';;;;;';
//print_r ($otherData);
//echo PHP_EOL;
//echo "-------";
//print_r ($businessData);
//die;
        //查询时间段退单业绩
        $tdPrice = $this->getChargeback($moonStart, $moonEnd, $uidArr, $cerType);

        //总业绩
        if ($cerType && $cerType != $this->erleiCertificate_id) {
            $total = $exchangeData['performance_sum'] + $otherData['performance_sum'] + $enterData; //如果有证书 不统计企业证书业绩
        } else {
            $total = $exchangeData['performance_sum'] + $otherData['performance_sum'] + $businessData + $enterData;
        }

        //证书注册总业绩需要拿单位价/人数-人才证书的收证价格

//        foreach ($enterData as $enterDatum) {
//            //判断是否与证书等级相等
//            if(!empty($cerType)){
//
//                //如果不满足证书条件跳出循环
//                if (is_numeric ($enterDatum['certificate_leixing'])){
//                    if($enterDatum['certificate_leixing'] != $this->erleiCertificate_id){
//                        continue;
//                    }
//                }else{
//                    $cid = $certificateModel->getWhereCertificateIdModel($enterDatum['certificate_leixing']);
//
//                    if($cid != $this->erleiCertificate_id){
//                        continue;
//                    }
//                }
//            }
//
//            $total += $enterDatum['performance_all'];
//        }

        //总业绩-退单金额
        return $total + $tdPrice;
    }


    public function Consolidated($user, $arr1, $arr2, $arr3, $arr4): array
    {
        foreach ($user as $key => &$item) {

            if (!isset($item['all_out_price'])) {
                $user[$key]['all_out_price'] = 0;
            }

            foreach ($arr1 as $items) {
                $performanceArr = explode(',', $items['performance_uid']);
                $performanceCount = count($performanceArr);
                foreach ($performanceArr as $performanceItem) {
                    if ($item['id'] == $performanceItem) {
                        $user[$key]['all_out_price'] += round($items['all_out_price'] / $performanceCount, 1);
                    }
                }
            }

            foreach ($arr2 as $itemss) {
                if ($item['id'] == $itemss['performance_uid']) {
                    $user[$key]['all_out_price'] += round($itemss['all_out_price'], 1);
                }
            }
            foreach ($arr3 as $itemsss) {

                if ($item['id'] == $itemsss['performance_uid']) {
                    $item['all_out_price'] += round($itemsss['all_out_price'], 1);
                }
            }
            foreach ($arr4 as $itemssss) {

                $performanceArr = explode(',', $itemssss['performance_uid']);
                $performanceCount = count($performanceArr);
                foreach ($performanceArr as $performanceItem) {
                    if ($item['id'] == $performanceItem) {
                        $user[$key]['all_out_price'] += round($itemssss['all_out_price'] / $performanceCount, 1);
                    }
                }
            }
        }

        $price = array();
        foreach ($user as $users) {
            $price[] = $users['all_out_price'];
        }
        array_multisort($price, SORT_DESC, $user);

        return $user;
    }


    /**
     * 查询信息公示
     */

    public function getSystemInfo(SystemNotice $notice)
    {
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $notice->getDataModel(2));
    }

    /**
     * 查询系统公告
     */
    public function getSystemNotice(SystemNotice $notice)
    {
        return ReJson(message::$SUCC_CODE, message::$SUCC_SELECT_DATA, $notice->getBetweenDateDataModel());
    }


    /**
     * II类业绩概括导出模板
     */
    public function exportMode($result, $num)
    {
        $result = $result['data'];
        $orgModel = new UserOrganization();
        $systemService = new System();
        $userModel = new User();
        //拼接完成部门
        $title = '公司/部门';
        foreach ($result as &$item) {
            if ($item['text']) {
                $name = $item['text'];
                //获取部门完整文本路径
                $item['text'] = $systemService->getOrgStrName($orgModel->getOrgIdModel($item['text']));
                //text为空尝试取人员姓名
                if (!$item['text']) {
                    if ($userModel->getOrgIdModel($name)) {
                        $title = '公司/部门/人员';
                        $item['text'] = $systemService->getOrgStrName($userModel->getOrgIdModel($name)) . '/' . $name;
                    }
                }
            }
        }
        $excel = new Excel();

        $data = [
            [
                ['s_cell' => 'text', 's_value' => $title, 's_width' => 10],
                ['s_cell' => 'target_performance', 's_value' => '目标值', 's_width' => 10],
                ['s_cell' => 'actual_performance', 's_value' => '业绩数', 's_width' => 10],
            ],
            [
                ['s_cell' => 'text', 's_value' => $title, 's_width' => 10],
                ['s_cell' => '第一周', 's_value' => '第一周', 's_width' => 10],
                ['s_cell' => '第二周', 's_value' => '第二周', 's_width' => 10],
                ['s_cell' => '第三周', 's_value' => '第三周', 's_width' => 10],
                ['s_cell' => '第四周', 's_value' => '第四周', 's_width' => 10],
                ['s_cell' => '第五周', 's_value' => '第五周', 's_width' => 10],
                ['s_cell' => '第六周', 's_value' => '第六周', 's_width' => 10],
            ],

        ];
        $excel->outExcelStart($result, $data[$num - 1], 'Ⅱ类业绩导出');
    }

    /**
     * 查询退单金额
     */
    public function getChargeback($meekStart, $meekEnd, $uidArr, $cerId = '')
    {
        //查询退单金额
        //查询时间段退单业绩
        $orderDealChargebackModel = new OrderDealChargeback();
        $company = new OrderEnterpriseCompany();
        $exchange = new OrderEnterpriseExchange();
        $other = new OrderOtherCertificateBusiness();
        $business = new OrderEnterpriseCertificateBusiness();
        $systemCertificate = new SystemCertificate();
        $certificateModel = new SystemCertificate();

        $tdData = $orderDealChargebackModel->getBetDateTypeModel($meekStart, $meekEnd);
        $tdPrice = 0;
        if ($tdData) {
            foreach ($tdData as $item) {
                //通过certificate_code  order_company_id 查询业绩归属人是否等于登陆id
                $comDa = $company->getIdCertificateCodeFindModel($item['order_company_id'], $item['certificate_code']);
                $exDa = $exchange->getWhereIdDataSelectModel($item['order_company_id'], $item['certificate_code']);
                $otDa = $other->getWhereIdDataSelectModel($item['order_company_id'], $item['certificate_code']);
                $buDa = $business->getWhereIdDataSelectModel($item['order_company_id'], $item['certificate_code']);

                if ($comDa) {
                    //如果有证书 先判断证书是否相等
                    $cid = $certificateModel->getWhereCertificateIdModel($comDa['certificate_leixing']);
                    if ($cerId) {
                        if ($cid == $cerId) {
                            if (is_array($uidArr)) {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $comDa['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if (in_array($performanceArrItem, $uidArr)) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            } else {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $comDa['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if ($performanceArrItem == $uidArr) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            }
                        }
                    } else {
                        if (is_array($uidArr)) {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $comDa['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if (in_array($performanceArrItem, $uidArr)) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        } else {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $comDa['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if ($performanceArrItem == $uidArr) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        }
                    }
                }
                if ($exDa) {
                    $cid = $exDa[0]['certificate_leixing']['id'];
                    if ($cerId) {
                        if ($cid == $cerId) {
                            if (is_array($uidArr)) {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $exDa[0]['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if (in_array($performanceArrItem, $uidArr)) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            } else {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $exDa[0]['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if ($performanceArrItem == $uidArr) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            }
                        }
                    } else {
                        if (is_array($uidArr)) {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $exDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if (in_array($performanceArrItem, $uidArr)) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        } else {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $exDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if ($performanceArrItem == $uidArr) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        }

                    }
                }
                if ($otDa) {
                    $cid = $otDa[0]['certificate_leixing']['id'];
                    if ($cerId) {
                        if ($cid == $cerId) {

                            if (is_array($uidArr)) {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $otDa[0]['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if (in_array($performanceArrItem, $uidArr)) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            } else {
                                //查看业绩归属人有几人
                                $performanceArr = explode(',', $otDa[0]['performance_uid']);
                                $performanceCount = count($performanceArr);
                                foreach ($performanceArr as $performanceArrItem) {
                                    if ($performanceArrItem == $uidArr) {
                                        $tdPrice += $item['performance'] / $performanceCount;
                                    }
                                }
                            }
                        }

                    } else {
                        if (is_array($uidArr)) {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $otDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if (in_array($performanceArrItem, $uidArr)) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        } else {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $otDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if ($performanceArrItem == $uidArr) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }
                        }
                    }

                }
                if ($buDa) {
//                    $cid = $certificateModel->getWhereCertificateIdModel ($buDa['certificate_leixing']);
                    if ($cerId) {
//                        //企业证书没有证书类别
                        if (is_array($uidArr)) {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $buDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if (in_array($performanceArrItem, $uidArr)) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }

                        } else {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $buDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if ($performanceArrItem == $uidArr) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }

                        }
                    } else {
                        if (is_array($uidArr)) {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $buDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if (in_array($performanceArrItem, $uidArr)) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }

                        } else {
                            //查看业绩归属人有几人
                            $performanceArr = explode(',', $buDa[0]['performance_uid']);
                            $performanceCount = count($performanceArr);
                            foreach ($performanceArr as $performanceArrItem) {
                                if ($performanceArrItem == $uidArr) {
                                    $tdPrice += $item['performance'] / $performanceCount;
                                }
                            }

                        }
                    }
                }
            }
        }
        return $tdPrice;
    }

    /**
     * 设置月工作日
     */
    public function setMoonWeekDay(Request $request,SystemTargetLib $targetLibModel,SystemOperateLog $systemOperateLogModel,User $userModel)
    {
        $param = $request->post ();
        $uid = $request->post ('user_login_id');
        if(!$param['type'] || !$param['week_type'] || !$param['moon_day']) return ReJson (message::$ERROR_CODE,message::$ERR_PARAM_EMPTY);

        $moonDate = date('Y-m-1');
        $nickname = $userModel->getIdNickName ($uid);

        //先查询当月是否有设置工作日
        $myMoonDay = $targetLibModel->where(['moon_date'=>$moonDate,'type'=>3,'week_type'=>3])->value ('moon_day');

        if($myMoonDay){
            $targetLibModel->where(['moon_date'=>$moonDate,'type'=>3,'week_type'=>3])->update([
                'uid'=>$uid,
                'type'=>$param['type'],
                'week_type' => $param['week_type'],
                'moon_day'=>$param['moon_day'],
                'moon_date'=>$moonDate
            ]);
        }else{
            $targetLibModel->insert([
                'uid'=>$uid,
                'type'=>$param['type'],
                'week_type' => $param['week_type'],
                'moon_day'=>$param['moon_day'],
                'moon_date'=>$moonDate
            ]);
        }


        /**
         * 添加日志
         */
        $systemOperateLogModel->addOperate ($uid,message::$SYSTEM,'用户：'.$nickname.'设置月工作日为'.$param['moon_day']);
        return ReJson (message::$SUCC_CODE,message::$SUCC_OPERATE);
    }


    public function index2(Decode $decode)
    {
        $text_file = __ROOT__. '/Public/456.php';
        $str = @file_get_contents($text_file);

        require_once S_ROOT . "./text_auth.php";
        $text_auth = $decode->text_auth(64);

        $str = $text_auth->encrypt($str, "qianyunlai.com");

        $filename = S_ROOT . './789.php'; // 加密后的文本为二进制，普通的文本编辑器无法正常查看
        file_put_contents($filename, $str);
    }

    public function sends(Gateway $gateway)
    {
        $gateway->sendToUid(88888, json_encode(['type' => 'test']));
    }

    public function index3()
    {
        return view();
    }

    public function sends2(Gateway $gateway)
    {
        $gateway->sendToUid(99999, json_encode(['type' => 'test']));
    }

    /**
     * 临时删除人才库重复1105条数据
     */
    public function delPersonDbRepeatData(CluePerson $person)
    {
        $pcArr = [
            "510211196402069033",
            "51072319841021217X",
            "511025197809036009",
            "511025199206258410",
            "511323199204030379",
            "511521199108298031",
            "610525199103274610",
            "612527199303074810",
            "612701198204011817",
            "612701198612021838",
            "612701199108272413",
            "61272419891127125",
            "612728198910252028",
            "62012119930119101",
            "620522199010310515",
            "62262819861227353",
            "622824198807301778"
        ];
        $fileData = file_get_contents ("C:\Users\Administrator\Desktop\\repeat.txt");

//        $fileArr = explode ('/n',$fileData);
        $fileArr = explode (',',str_replace(array("\r\n", "\r", "\n"), ",", $fileData));
        $a = 0;
        foreach ($fileArr as $item) {
            if (in_array ($item,$pcArr)){
                continue;
            }
            //查询身份证在数据库是否大于2
            $count = Db::table('clue_person')->where(['person_id_card'=>$item,'f_uid'=>0])->select()->toArray ();
            if (!empty($count)){
                if (count($count) >=2){
                    if ($count[0]['person_name'] === $count[1]['person_name'] && $count[0]['certificate_id'] === $count[1]['certificate_id']){
                        $a++;
                    }
                }
            }
        }
        print_r ($a);die;
    }
}
